# get all facebook applications name


INPUT_DIR = "./facebook_payload_with_cookie/mobile/"

REG_EXPRESS = /(apps.facebook.com)\/([a-zA-Z0-9_-]+)\//

module GetFacebookApp
  def self.get_all_files
    Common.get_all_files(INPUT_DIR)
  end

  def self.handle_all_files(all_files)
    puts ">> get facebook apps"
    facebook_app_mapping = {}

    all_files.each do |file_name|
      # return_array = 
      mapping = handle_each_file file_name

      # facebook_id_array = facebook_id_array + return_array.uniq
      mapping.each do |key, value|
        if facebook_app_mapping.has_key? key
          facebook_app_mapping[key] = facebook_app_mapping[key] + value 
        else
          facebook_app_mapping[key] = value 
        end
      end
    end

    # facebook_id_array.uniq
    facebook_app_mapping
  end

  def self.handle_each_file(file_name)
    puts "now handling : " + file_name
    file = File.open INPUT_DIR + file_name, "r"

    facebook_app_mapping = {}

    begin
      while line = file.readline
        # fields = line.split("|")
        if line.include? "apps.facebook.com"
          if REG_EXPRESS.match line
            app_name = $2
            if facebook_app_mapping.has_key? app_name
              facebook_app_mapping[app_name] = facebook_app_mapping[app_name] + 1
            else
              facebook_app_mapping[app_name] = 1
            end
          end
        end
      end
    rescue Exception => e
      puts e.to_s
    end

    facebook_app_mapping
  end

  def self.run
    puts ">> start to get facebook urls ..."

    begin
      all_files = GetFacebookApp.get_all_files      
      all_mapping = GetFacebookApp.handle_all_files all_files

      output = File.open "facebook_mobile_app_urls.csv", "w"
      all_mapping.each { |key, value| output.puts "#{key.to_s},#{value}" }
      output.close

      puts ">> end to get facebook IDs"
    rescue Exception => e
      puts ">> EEROR:"
      puts e.to_s
    end
  end
end
